/*
 * Copyright (C) 2013 yixia.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.football.fragment.news;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener;
import io.vov.vitamio.MediaPlayer.OnErrorListener;
import io.vov.vitamio.MediaPlayer.OnInfoListener;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.utils.Log;
import io.vov.vitamio.widget.CenterLayout;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.football.R;
import com.football.activity.video.ScreenActivity;
import com.football.adapter.ChannelListAdapter;
import com.football.database.ChannelOperation;
import com.football.model.Channel;

//import android.media.MediaRecorder;

public class VideoViewBuffer extends Fragment implements OnInfoListener,
		OnBufferingUpdateListener/* , SurfaceHolder.Callback */, Callback,
		OnClickListener {

	private static final String TAG = "TAG";
	/**
	 * TODO: Set the path variable to a streaming video URL or a local media
	 * file path.
	 */
	private static String path = "";
	private Uri uri;
	private VideoView mVideoView;
	private View view;
	private ProgressBar pb;
	private View favoriteChannel;
	private TextView downloadRateView, loadRateView;
	private EditText streamName, streamUrl;
	private ListView listViewChannel;
	private ArrayList<Channel> listChannel;
	private MediaController mediaController;
	private ChannelOperation channelDBoperation;
	private ProgressBar probar;
	private ImageButton mRecording, addNew;
	MediaRecorder recorder;
	SurfaceHolder holder;
	boolean recording = false;
	private boolean isRecord = false;
	ChannelListAdapter adapter;
	CenterLayout videoLayout;
	LinearLayout addStreamArea;
	Integer currentBufferSize;

	// ImageButton recordBtn;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.videobuffer, container, false);
		favoriteChannel = (View) view.findViewById(R.id.favorite_channel);
		videoLayout = (CenterLayout) view.findViewById(R.id.video_layout);
		addStreamArea = (LinearLayout) view.findViewById(R.id.add_channel_area);

		mVideoView = (VideoView) view.findViewById(R.id.buffer);
		android.view.ViewGroup.LayoutParams layoutParams = videoLayout
				.getLayoutParams();
		layoutParams.height = 291;
		videoLayout.setLayoutParams(layoutParams);
		// mVideoView.setLayoutParams(layoutParams);

		pb = (ProgressBar) view.findViewById(R.id.probar);
		downloadRateView = (TextView) view.findViewById(R.id.download_rate);
		loadRateView = (TextView) view.findViewById(R.id.load_rate);
		streamUrl = (EditText) view.findViewById(R.id.stream_url);
		streamName = (EditText) view.findViewById(R.id.stream_name);
		addNew = (ImageButton) view.findViewById(R.id.btn_addnew);
		addNew.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (streamUrl.getText() != null
						&& !streamUrl.getText().toString().equals("")
						&& !streamUrl.getText().toString().trim().equals("")
						&& streamName.getText() != null
						&& !streamName.getText().toString().equals("")
						&& !streamName.getText().toString().trim().equals("")) {
					channelDBoperation.close();
					channelDBoperation.open();
					channelDBoperation.addChannel(streamName.getText()
							.toString(), streamUrl.getText().toString(), "des");
					Toast.makeText(getActivity(), "Save", Toast.LENGTH_SHORT)
							.show();
					listChannel = channelDBoperation.getAllChannels();
					reloadAllData();
					streamUrl.clearComposingText();
					streamName.clearComposingText();
				}
			}
		});
		// mVideoView.setVisibility(ViewGroup.GONE);
		channelDBoperation = new ChannelOperation(getActivity());
		channelDBoperation.open();
		mediaController = new MediaController(this.getActivity());
		// recordBtn = (ImageButton) view.findViewById(R.id.btn_recording);
		// recordBtn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// // prepareRecorder();
		// if (mVideoView.isPlaying() && currentUrl != null) {
		// try {
		// getDataSource(currentUrl);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// }
		// }
		// });

		listChannel = channelDBoperation.getAllChannels();
		probar = (ProgressBar) view.findViewById(R.id.probar);
		probar.setVisibility(ViewGroup.GONE);
		createBasicData();

		listViewChannel = (ListView) view
				.findViewById(R.id.listFavoriteChannel);

		adapter = new ChannelListAdapter(getActivity(), listChannel);
		listViewChannel.setAdapter(adapter);

		listViewChannel.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mVideoView.setVisibility(ViewGroup.VISIBLE);
				Toast.makeText(getActivity(), "Starting...", Toast.LENGTH_LONG)
						.show();
				startPlayUrl(listChannel.get(position).getName(), listChannel
						.get(position).getUrl());
			}
		});
		listViewChannel
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> adapter,
							View arg1, int position, long id) {
						channelDBoperation.close();
						channelDBoperation.open();
						channelDBoperation.deleteChannel(listChannel.get(
								position).getId());
						Toast.makeText(getActivity(), "Deleted",
								Toast.LENGTH_SHORT).show();
						listChannel = channelDBoperation.getAllChannels();
						reloadAllData();
						return true;
					}
				});

		Context context = getActivity();
		SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		currentBufferSize = sharedPrefs.getInt("speechRate", 10);
		Toast.makeText(context, currentBufferSize + "", Toast.LENGTH_LONG)
				.show();
		return view;
	}

	/**
	 * helper to show what happens when all data is new
	 */
	private void reloadAllData() {
		// get new modified random data
		List<Channel> objects = listChannel;
		// update data in our adapter
		adapter.getChannelList().clear();
		adapter.getChannelList().addAll(objects);
		// fire the event
		adapter.notifyDataSetChanged();
	}

	private void createBasicData() {
		if (listChannel == null || listChannel.isEmpty()) {
			channelDBoperation
					.addChannel(
							"Bipbopall",
							"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8",
							"des");
			channelDBoperation
					.addChannel(
							"Rossija",
							"http://euro.online.hls.cn.ru/streaming/rossija/126/tvrec/playlist.m3u8",
							"des");
			channelDBoperation
					.addChannel(
							"NTV",
							"http://euro.online.hls.cn.ru/streaming/ntv/126/tvrec/playlist.m3u8",
							"des");
			channelDBoperation
					.addChannel(
							"Kanal",
							"http://euro.online.hls.cn.ru/streaming/5kanal/126/tvrec/playlist.m3u8",
							"des");
			channelDBoperation
					.addChannel(
							"SMILE",
							"http://euro.online.hls.cn.ru/streaming/smile/126/tvrec/playlist.m3u8",
							"des");
			channelDBoperation
					.addChannel(
							"Futbol",
							"http://euro.online.hls.cn.ru/streaming/futbol/126/tvrec/playlist.m3u8",
							"des");
		}
	}

	String currentUrl = null;

	private void startPlayUrl(String name, String url) {
		/*
		 * Alternatively,for streaming media you can use
		 * mVideoView.setVideoURI(Uri.parse(URLstring));
		 */
		currentUrl = url;
		if (mVideoView.isPlaying()) {
			mVideoView.destroyDrawingCache();
			mVideoView.stopPlayback();
			mVideoView.refreshDrawableState();
			downloadRateView.setText("");
			loadRateView.setText("");

		}
		((ScreenActivity) getActivity()).getCurrentWatching().setText(name);
		probar.setVisibility(ViewGroup.VISIBLE);
		downloadRateView.setVisibility(View.VISIBLE);
		loadRateView.setVisibility(View.VISIBLE);

		uri = Uri.parse(url);
		mVideoView.setVideoURI(uri);
		android.view.ViewGroup.LayoutParams layoutParams = videoLayout
				.getLayoutParams();
		layoutParams.height = 291;
		videoLayout.setLayoutParams(layoutParams);

		mVideoView.setMediaController(mediaController);
		mVideoView.requestFocus();
		mVideoView.setOnInfoListener(this);
		mVideoView.setBufferSize(1024 * 1024 * currentBufferSize /* 5 */);
		mVideoView.setVideoQuality(16);
		mVideoView.setOnBufferingUpdateListener(this);
		mVideoView.setClickable(true);
		mVideoView.setOnClickListener(this);
		mVideoView.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				probar.setVisibility(ViewGroup.GONE);
				return false;
			}
		});

		mVideoView.setOnPreparedListener(new OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mediaPlayer) {
				// optional need Vitamio 4.0
				mediaPlayer.setPlaybackSpeed(1.0f);
				mediaPlayer.setCacheDirectory(Environment
						.getExternalStorageDirectory() + "/euro_video.mp4");
				// mediaPlayer.getMetadata().getByteArray(TRIM_MEMORY_BACKGROUND);
				// mVideoView.setBackground(null);

			}
		});

	}

	@Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		switch (what) {
		case MediaPlayer.MEDIA_INFO_BUFFERING_START:
			if (mVideoView.isPlaying()) {
				mVideoView.pause();
				pb.setVisibility(View.VISIBLE);
				downloadRateView.setText("");
				loadRateView.setText("");
				downloadRateView.setVisibility(View.VISIBLE);
				loadRateView.setVisibility(View.VISIBLE);

			}
			break;
		case MediaPlayer.MEDIA_INFO_BUFFERING_END:
			mVideoView.setBackgroundResource(0);
			mVideoView.start();
			pb.setVisibility(View.GONE);
			downloadRateView.setVisibility(View.GONE);
			loadRateView.setVisibility(View.GONE);

			break;
		case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:
			downloadRateView.setText("" + extra + "kb/s" + "  ");
			break;
		}

		return true;
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		loadRateView.setText(" Buffer " + percent + "%");

	}

	public View getFavoriteChannel() {
		return favoriteChannel;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onStop() {
		super.onStop();
		mVideoView.stopPlayback();
		channelDBoperation.close();
	}

	@Override
	public void onPause() {
		mVideoView.pause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mVideoView.resume();
		super.onResume();

	}

	public MediaController getMediaController() {
		return mediaController;
	}

	public void setMediaController(MediaController mediaController) {
		this.mediaController = mediaController;
	}

	boolean isInit = false;

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		// prepareRecorder();

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		if (recording) {
			recorder.stop();
			recording = false;
		}
		recorder.release();
		getActivity().finish();
	}

	private String getDataSource(String path) throws IOException {
		if (!URLUtil.isNetworkUrl(path)) {
			return path;
		} else {
			URL url = new URL(path);
			URLConnection cn = url.openConnection();
			cn.connect();
			InputStream stream = cn.getInputStream();
			if (stream == null)
				throw new RuntimeException("stream is null");
			File temp = File.createTempFile("euro_" + Math.random(), "mp4",
					Environment.getExternalStorageDirectory());
			// temp.deleteOnExit();
			String tempPath = temp.getAbsolutePath();
			FileOutputStream out = new FileOutputStream(temp);
			byte buf[] = new byte[128];
			do {
				int numread = stream.read(buf);
				if (numread <= 0)
					break;
				out.write(buf, 0, numread);
			} while (true);
			try {
				stream.close();
			} catch (IOException ex) {
				Log.e(TAG, "error: " + ex.getMessage(), ex);
			}
			return tempPath;
		}
	}

	public void waitForFocus() {
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				// camera = Camera.open(0);
				// camera.unlock();
				// recorder.set
				// recorder.setCamera(camera);
				recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
				recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
				recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
				// Step 1: Get camera instance and initialise MediaRecorder
				// CamcorderProfile cpHigh = CamcorderProfile.get(0,
				// CamcorderProfile.QUALITY_LOW);
				// recorder.setProfile(cpHigh);
				String mFileName = Environment.getExternalStorageDirectory()
						.getAbsolutePath();
				mFileName = mFileName
						+ "/videocapture_example.mp4"
						+ java.text.DateFormat.getDateTimeInstance().format(
								Calendar.getInstance().getTime()) + ".mp4";
				recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
				recorder.setPreviewDisplay(holder.getSurface());
				recorder.setOutputFile(mFileName);
				recorder.setMaxDuration(10000); // 10 seconds
				recorder.setMaxFileSize(400000); // Approximately 1 megabytes

				Handler handler1 = new Handler();
				handler1.postDelayed(new Runnable() {
					@Override
					public void run() {
						try {
							recorder.prepare();
							recorder.setCaptureRate(TRIM_MEMORY_BACKGROUND);
							recorder.start();
						} catch (RuntimeException e) {
							Log.e("TAG", e.getMessage());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}, 2000);

			}
		}, 2000);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	public LinearLayout getAddStreamArea() {
		return addStreamArea;
	}

	public void setAddStreamArea(LinearLayout addStreamArea) {
		this.addStreamArea = addStreamArea;
	}

}
